import cv2
import numpy as np
import time
import pygame

def play_video_with_countdown(video_path):
    # 初始化pygame用于播放音频
    pygame.init()
    pygame.mixer.init()
    
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    # 打开摄像头
    cam = cv2.VideoCapture(0)
    cam.set(cv2.CAP_PROP_FRAME_WIDTH, frameWidth)
    cam.set(cv2.CAP_PROP_FRAME_HEIGHT, frameHeight)
    
    # 创建视频写入对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out_single = cv2.VideoWriter('single.mp4', fourcc, fps, (frameWidth, frameHeight))
    out_compare = cv2.VideoWriter('compare.mp4', fourcc, fps, (frameWidth*2, frameHeight))
    
    # 倒计时
    for i in range(3, 0, -1):
        ret, frame = cam.read()
        if ret:
            cv2.putText(frame, str(i), (frameWidth//2-50, frameHeight//2), 
                        cv2.FONT_HERSHEY_SIMPLEX, 4, (0, 255, 0), 4)
            cv2.imshow('Camera', frame)
            cv2.waitKey(1000)
    
    # 加载音频
    try:
        pygame.mixer.music.load(video_path)
        pygame.mixer.music.play()
    except:
        print("无法加载音频")
    
    while True:
        ret1, video_frame = cap.read()
        ret2, cam_frame = cam.read()
        
        if not ret1:
            break
            
        if ret2:
            # 处理摄像头画面（不使用YOLO）
            # 这里可以直接使用摄像头画面，不进行姿态检测
            # 例如，您可以在摄像头画面上添加一些简单的处理
            cam_frame = cv2.putText(cam_frame, "Camera Feed", (10, 30), 
                                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

            # 保存单独的摄像头画面
            out_single.write(cam_frame)
            
            # 合并两个画面
            combined_frame = np.hstack((video_frame, cam_frame))
            out_compare.write(combined_frame)
            
            # 显示画面
            cv2.imshow('Video', video_frame)
            cv2.imshow('Camera', cam_frame)
            
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # 释放资源
    pygame.mixer.music.stop()
    pygame.quit()
    cap.release()
    cam.release()
    out_single.release()
    out_compare.release()
    cv2.destroyAllWindows()

# 主程序入口
if __name__ == "__main__":
    play_video_with_countdown("test.mp4")
